package com.company.woye.hotmove;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.hotmove.adapter.HotMoveQuQanAdapter;
import com.company.woye.hotmove.bean.QuaryQuantity;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.ScannerManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class QuaryQuantityActivity extends BaseActivity {

    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.ed_code)
    EditText edCode;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.ed_order)
    EditText edOrder;
    @BindView(R.id.ed_color)
    EditText edColor;
    @BindView(R.id.ed_size)
    EditText edSize;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.lv)
    ListView lv;
    @BindView(R.id.rl)
    LinearLayout rl;
    @BindView(R.id.tv_result)
    TextView tvResult;
    private ScannerManager scannerManager;
    String OrderNo = "", Size = "", Color = "", curLoginUserNo = "", workDate = "";
    private final int MSG_ERROR = 9001;
    private final int MSG_SCAN = 9002;
    private JSONArray searchJson;
    private List<QuaryQuantity> quaryQuantityList = new ArrayList<>();
    private HotMoveQuQanAdapter adapter;
    String curEmpNo="",curEmpName="",CurStationNo="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=this.getIntent().getExtras();
        curEmpNo=bundle.getString("EmpNo",curEmpNo);
        curEmpName=bundle.getString("EmpName",curEmpName);
        CurStationNo=bundle.getString("SiteNo",CurStationNo);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_quary_quantity;
    }

    @Override
    public void initView() {
        adapter = new HotMoveQuQanAdapter(this, quaryQuantityList);
        lv.setAdapter(adapter);
        tvData.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        curLoginUserNo = MyApplication.curLoginUserNo;
        edCode.requestFocus();
        edCode.requestFocusFromTouch();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code, String deviceName) {
                edCode.setText(code);
                queryDetail("SEARCH", MSG_SCAN);
            }
        }, edCode.getContext());
        edCode.setInputType(InputType.TYPE_NULL);
        edCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edCode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edCode, InputMethodManager.SHOW_FORCED);
            }
        });
        edCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    Log.e("Debug", "-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        System.out.println(edCode.getText().toString());
                        queryDetail("SEARCH", MSG_SCAN);
                        return true;
                    }
                }
                return false;
            }
        });
    }

    private void queryDetail(String OPERTYPE, int MSG) {
        hideIM(edCode);
        OrderNo = edOrder.getText().toString().trim();
        Color = edColor.getText().toString().trim();
        Size = edSize.getText().toString().trim();
        workDate = tvData.getText().toString();
        String sqlcmd = "Exec KeyPoint_Hot_Query @OperType='" + OPERTYPE + "',@BarCode='" + edCode.getText().toString()
                + "',@OrderNo='" + OrderNo + "',@Color='" + Color + "',@Size='" + Size
                + "',@UserNo='" + curLoginUserNo + "',@WorkDate='" + workDate + "',@EmpNo='" + curEmpNo+ "',@SiteNo='" + CurStationNo+ "'";
        ReadSQLData(sqlcmd, MSG);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm, int MSGS) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray;
                    System.out.println("过程:" + SQLComm);
                    jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println("结果" + jsonArray);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        //查询
                        if (jsonArray.optJSONObject(0).getString("OperType").equals("SEARCH") == true) {
                            searchJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSGS;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSGS;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                }

            }

        };
        new Thread(run).start();

    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ERROR:
                    Bundle bundle1 = msg.getData();
                    AlertDialog alertDialog1 = new AlertDialog.Builder(QuaryQuantityActivity.this)
                            .setTitle(getString(R.string.app_name)).setMessage(bundle1.getString("HintInfo"))
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create();
                    alertDialog1.show();
                    break;
                case MSG_SCAN:
                    //扫描
                    if (searchJson != null && searchJson.length() > 0) {
                        try {
                            if (searchJson.getJSONObject(0).has("ResultInfo")) {
                                tvResult.setText(searchJson.getJSONObject(0).getString("ResultInfo"));
                            }
                            if (searchJson.getJSONObject(0).has("ErrInfo")) {
                                AlertDialog alertDialog = new AlertDialog.Builder(QuaryQuantityActivity.this)
                                        .setTitle(getString(R.string.app_name)).setMessage(searchJson.getJSONObject(0).getString("ErrInfo"))
                                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                return;
                                            }
                                        }).create();
                                alertDialog.show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        List<QuaryQuantity> quaryQuantities = new Gson().fromJson(String.valueOf(searchJson), new TypeToken<List<QuaryQuantity>>() {
                        }.getType());
                        quaryQuantityList.clear();
                        quaryQuantityList.addAll(quaryQuantities);
                        adapter.notifyDataSetChanged();

                    } else {
                        quaryQuantityList.clear();
                        adapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @OnClick({R.id.iv_on_package_back, R.id.tv_on_package_back, R.id.tv_data, R.id.tv_clear, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            case R.id.tv_data:
                showDatePickDlg();
                break;
            case R.id.tv_clear:
                edOrder.setText("");
                edColor.setText("");
                edSize.setText("");
                break;
            case R.id.tv_search:
                queryDetail("SEARCH", MSG_SCAN);
                break;
        }
    }

    public void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(QuaryQuantityActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String month;
                if ((monthOfYear + 1) < 10) {
                    month = "0" + (monthOfYear + 1);
                } else {
                    month = (monthOfYear + 1) + "";
                }
                tvData.setText(year + "-" + (month) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();

    }
}

